package com.huhao.concurrency.example.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class ConditionExample {
    /**
     * 21:39:55.905 [Thread-0] INFO com.huhao.concurrency.example.lock.ConditionExample - wait signal
     * 21:39:55.913 [Thread-1] INFO com.huhao.concurrency.example.lock.ConditionExample - *get Lock
     * 21:39:58.914 [Thread-1] INFO com.huhao.concurrency.example.lock.ConditionExample - send signal ~
     * 21:39:58.914 [Thread-0] INFO com.huhao.concurrency.example.lock.ConditionExample - get signalL
     *
     * @param args
     */
    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        new Thread(() -> {
            try {
                reentrantLock.lock();
                log.info("wait signal");    //  1 等着人家发送信号说可以执行了，调用await等待
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("get signalL");    // 4 3释放了锁并发送了信号，我就获取到信号，释放锁，执行吧
            reentrantLock.unlock();
        }).start();

        new Thread(() -> {
            reentrantLock.lock();
            log.info("*get Lock"); // 2 上面那个线程等待了，我就也获取锁
            try {
                //模拟业务处理。。。
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            condition.signalAll();
            log.info("send signal ~ "); // 3 业务处理好了，发送信号，并释放锁
            reentrantLock.unlock();
        }).start();

    }
}
